package find;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class FindSimilar {
	
	static String sample = "sample_new.txt";
	static String sample_good = "sample_good.txt";
	static String sample_match = "sample_match.txt";
	
	static ArrayList<Node> list = new ArrayList<Node>();
	
	public static void main(String[] args) throws IOException {
		init();
		find();
	}
	
	static void init() throws IOException {
		BufferedReader br = new BufferedReader(new FileReader(sample_good));
		String line = br.readLine(), tarr[];
		int count = 0;
		while (line != null) {
			tarr = line.split("\t");
			list.add(new Node(tarr[0], Integer.parseInt(tarr[1]), Integer
					.parseInt(tarr[2])));
			++count;
			line = br.readLine();
		}
		br.close();
		System.out.println("Init finished: " + count + " lines read...");
	}
	
	final static int END = 14000000;
	static void find() throws IOException {
		BufferedReader br = new BufferedReader(new FileReader(sample));
		BufferedWriter bw = new BufferedWriter(new FileWriter(sample_match));
		
		Node node = new Node();
		String line = br.readLine(), tarr[];
		
		for (int i = 0; i < END && line != null; ++i) {
			tarr = line.split("\t");
			if (tarr.length == 3) {
				node = node.getInstance(tarr[0], Integer.parseInt(tarr[1]), Integer.parseInt(tarr[2]));
				findOutput(bw, node);
			}
			line = br.readLine();
			if (i % 10000 == 0) {
				System.out.println(i + " Processed");
			}
		}
		
		br.close();
		bw.close();
	}
	
	final static int  MDIST = 10;
	static void findOutput(BufferedWriter bw, Node n) throws IOException {
		for (Node node: list) {
			if (node.distance(n) < MDIST && !node.equals(n) && node.getQuality() < 1.5) {
				bw.write(node.toString());
				bw.newLine();
				bw.write(n.toString());
				bw.newLine();
				bw.newLine();
			}
		}
	}

}

class Node {
	String str;
	int freq, click;
	
	Node() {};
	
	Node(String s, int f, int c) {
		getInstance(s, f, c);
	}
	
	Node getInstance(String s, int f, int c) {
		str = s;
		freq = f;
		click = c;
		return this;
	}
	
	public double getQuality() {
		return click * 1.0 / freq;
	}
	
	public boolean equals(Object n) {
		if (! (n instanceof Node))
			return false;
		Node m = (Node) n;
		return str.equals(m.str) && freq == m.freq && click == m.click;
	}
	
	public int distance(Node n) {
		return Util.charDistance(str, n.str);
	}
	
	public String toString() {
		StringBuffer sb = new StringBuffer(str);
		sb.append("\t").append(freq).append("\t").append(click);
		return sb.toString();
		
	}
}